import Vue from 'vue';
import axios from 'axios';
import router from '../router';

const tip = (msg, type = 'info', onClose) => {
  Vue.prototype.$message({
    message: msg,
    center: true,
    duration: 1000,
    type,
    onClose
  });
};

const toLogin = () => {
  router.replace({
    name: 'login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  });
};

const errorHandle = (status) => {
  switch (status) {
    case 401:
      toLogin();
      break;
    case 403:
      tip('登录过期，请重新登录', 'warning', () => {
        localStorage.removeItem('token');
        toLogin();
      });
      break;
    case 404:
      tip('请求资源不存在', 'warning');
      break;
    default:
      tip(status);
  }
};

const baseURL = {
  development: 'http://dbadmin.ixinkexin.com/',
  // development: '',
  production: 'http://dbadmin.ixinkexin.com/',
  test: 'http://dbadmin.ixinkexin.com/'
};
const instance = axios.create({
  baseURL: baseURL[process.env.NODE_ENV],
  timeout: 3000
});
// 设置post请求头
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

/**
 * 请求拦截
 */
instance.interceptors.request.use(
  config => config,
  error => Promise.reject(error)
);
/**
 * 响应拦截
 */
instance.interceptors.response.use(
  res => {
    const { data } = res;
    if (data.code === 0) {
      return Promise.resolve(data.data);
    }
    return Promise.reject(res);
  },
  error => {
    const { response } = error;
    if (response) {
      errorHandle(response.status, response.data.message);
      return Promise.reject(response);
    }
    // 断网处理
    return 1;
  }
);

export default instance;
